$(document).ready(function () {
    init();
});

function update() {
    var fenleiids = $(".contenta").val();
    var id = $("input[name='id']").val();
    var name = $("input[name='name']").val();
    var price = $("input[name='price']").val();
    var stock = $("input[name='stock']").val();
    var guarantee = $("input[name='guarantee']").val();

    $.ajax({
        url: "/cake/updateById",
        type: 'GET',
        data: {
            'id': id,
            'name': name,
            'price': price,
            'stock': stock,
            'guarantee': guarantee,
            'fenleiids': fenleiids
        },
        dataType: "JSON",
        traditional: true,
        async: false,
        success: function (res) {
            if (res.code == "201") {
                alert(res.msg);
            }
            window.location.href = "/cakeView/" + res.data.id;
        },
        error: function (e) {
            alert('发生错误')
        }
    })
}

function init() {

    var path = location.href;
    var id = path.substring(path.lastIndexOf("/") + 1)

    $.ajax({
        url: "/cake/findById",
        type: 'GET',
        data: {
            'id': id
        },
        dataType: "JSON",
        async: false,
        success: function (res) {
            if (res.code == "200") {
                var data = res.data;
                $(".id").val(data.id);
                $(".name").val(data.name);
                $(".price").val(data.price);
                $(".stock").val(data.stock);
                $(".guarantee").val(data.guarantee);

                var data2 = res.data2;
                var xlk = "";
                for (var i  = 0; i < data2.length; i ++){
                    xlk += "<option class='chosena' value=" + data2[i].id + ">" + data2[i].name + "</option>";
                }
                $(".contenta").html(xlk);
                $(".contenta").trigger("chosen:updated");

                var fl = [];
                for (var i = 0; i < data.fruits.length; i++) {
                    fl.push(data.fruits[i].id);
                }
                $(".contenta").val(fl);
                $(".contenta").trigger("chosen:updated");
            } else {
                alert(res.msg);
            }
        },
        error: function (e) {
            alert('发生错误')
        }
    })
}